package com.moshang.blog.controller.back.blog;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moshang.blog.core.annotation.SystemLog;
import com.moshang.blog.entity.SysDict;
import com.moshang.blog.entity.TbArticleInfo;
import com.moshang.blog.service.SysDictService;
import com.moshang.blog.service.TbArticleInfoService;
import com.moshang.blog.service.TbSortService;
import com.moshang.blog.core.utils.PageUtil;
import com.moshang.blog.core.utils.RestResponse;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @program: blog
 * @description: 文章管理
 * @author: xieweiwei
 * @create: 2018-11-16 14:49
 **/
@Controller
@RequestMapping("/back/blog/article")
public class TbArticleInfoController {
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private TbSortService tbSortService;
    @Autowired
    private TbArticleInfoService tbArticleInfoService;
    private final  String  prefix="back/blog/article/";

    /**
     * 进入文章管理页面
     */
    @GetMapping("list")
    public  String list(){
        return prefix+"list";
    }

    /**
     * 查询文章列表
     */
    @RequestMapping(value = "findList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "/findList", httpMethod = "POST", notes = "查询文章列表")
    public PageUtil<TbArticleInfo> findList(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                      @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                      ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        PageUtil<TbArticleInfo> tbArticleInfoPageUtil = new PageUtil<>();
        QueryWrapper<TbArticleInfo> tbArticleInfoQueryWrapper = new QueryWrapper<>();
        tbArticleInfoQueryWrapper.eq("is_activited",0);
        if(!map.isEmpty()){
            String status = (String) map.get("status");
            String isRecommend = (String) map.get("isRecommend");
            String isTop = (String) map.get("isTop");
            String title = (String) map.get("title");
            if(StringUtils.isNotBlank(status)) {
                tbArticleInfoQueryWrapper.eq("status", status);
            }
            if(StringUtils.isNotBlank(isRecommend)) {
                tbArticleInfoQueryWrapper.eq("is_recommend", isRecommend);
            }
            if(StringUtils.isNotBlank(isTop)) {
                tbArticleInfoQueryWrapper.eq("is_top", isTop);
            }
            if(StringUtils.isNotBlank(title)) {
                tbArticleInfoQueryWrapper.eq("title", title);
            }
        }
        tbArticleInfoQueryWrapper.orderByDesc("update_time");
        IPage<TbArticleInfo> tbArticleInfoPage = tbArticleInfoService.page(new Page<>(page,limit),tbArticleInfoQueryWrapper);
        tbArticleInfoPageUtil.setCount((int) tbArticleInfoPage.getTotal());
        tbArticleInfoPageUtil.setData(tbArticleInfoPage.getRecords());
        return tbArticleInfoPageUtil;

    }
    /**
     * 进入添加文章页面
     * @param model
     * @return
     */

    @GetMapping("addUI")
    public String addUI( Model model){
        JSONArray jsonArray = tbSortService.getTreeUtil(null);
        model.addAttribute("ztreeData", jsonArray);
        List<SysDict> sysDictList=sysDictService.findByCondition("文章标签");
        model.addAttribute("sysDictList",sysDictList);
        return prefix+"add";
    }
    /**
     * 提交博客
     */
    @ApiOperation(value = "/saveOrUpdate", httpMethod = "POST", notes = "保存或修改文章")
    @RequiresPermissions("blog:sort:add")
    @PostMapping("saveOrUpdate")
    @ResponseBody
    public RestResponse add(TbArticleInfo tbArticleInfo){
        try {
            if(StringUtils.isBlank(tbArticleInfo.getTitle())){
                return RestResponse.failure("标题不能为空");
            }
            if(StringUtils.isBlank(tbArticleInfo.getContent())){
                return RestResponse.failure("内容不能为空");
            }
            tbArticleInfoService.saveOrUpdateArticle(tbArticleInfo);

            return RestResponse.success();
        }catch (AuthorizationException a){
            throw  a;
        }

    }
    /**
     * 进入修改文章页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("editUI")
    public String editUI(Integer id,Model model){
        TbArticleInfo tbArticleInfo = tbArticleInfoService.findById(id);
        JSONArray jsonArray = tbSortService.getTreeUtil(null);
        model.addAttribute("ztreeData", jsonArray);
        List<SysDict> sysDictList=sysDictService.findByCondition("文章标签");
        model.addAttribute("sysDictList",sysDictList);
        model.addAttribute("tbArticleInfo",tbArticleInfo);
        return prefix+"edit";
    }


    @PostMapping("delete")
    @ResponseBody
    @SystemLog("删除文章(单个)")
    @ApiOperation(value = "/delete", httpMethod = "POST", notes = "删除文章")
    public RestResponse delete(@RequestParam(value = "id",required = false)Integer id){
        if(id == null || id == 0 || id == 1){
            return RestResponse.failure("参数错误");
        }
        TbArticleInfo tbArticleInfo = tbArticleInfoService.findById(id);
        if(tbArticleInfo == null){
            return RestResponse.failure("文章不存在");
        }
        tbArticleInfoService.removeById(id);
        return RestResponse.success();
    }

    @PostMapping("batchDelete")
    @ResponseBody
    @SystemLog("删除文章(单个)")
    @ApiOperation(value = "/batchDelete", httpMethod = "POST", notes = "批量删除文章")
    public RestResponse batchDelete(@RequestBody List<TbArticleInfo> articleInfos){
        if(articleInfos == null || articleInfos.size()== 0 ){
            return RestResponse.failure("请选择要删除的文章");
        }

        for (TbArticleInfo tbArticleInfo : articleInfos){

                tbArticleInfoService.removeById(tbArticleInfo.getId());
            }
        return RestResponse.success();
    }
    @PostMapping("findCountBySort")
    @ResponseBody
    public RestResponse findCountBySort(){
        return RestResponse.success().setData(tbArticleInfoService.findCountBySort());
    }
}
